import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index'
Vue.use(VueRouter)

const routes = [
  {
    path: '/', // 默认打开看到的路由
    component: () => import('@/views/layout/index'),
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: () => import('@/views/home/index')
      },
      {
        path: 'user-info',
        component: () => import('@/views/user/userinfo')
      },
      {
        path: 'user-avatar',
        component: () => import('@/views/user/userAvatar')
      },
      {
        path: 'user-pwd',
        component: () => import('@/views/user/userPwd')
      },
      {
        path: 'art-cate',
        component: () => import('@/views/article/artcate')
      },
      {
        path: 'art-list',
        component: () => import('@/views/article/artList')
      }

    ]
  },
  {
    path: '/reg',
    component: () => import('@/views/register/index')
    // webpack提供import函数来路由懒加载导入组件
    // 路由懒加载，就是页面路由路径切换到/reg,才去加载对应组件代码
    // 好处：让首页加载文件体积更 新，打开更快
  },
  {
    path: '/login',
    component: () => import('@/views/login/index')
  }
]

const router = new VueRouter({
  routes
})
const whiteList = ['/login', '/reg'] // 路由白名单
// 全局前置路由守卫
router.beforeEach((to, from, next) => {
  const token = store.state.token
  if (token) {
    if (!store.state.userinfo.username) {
      // 登录时发现vuex里没有用户信息并且有token才会发送请求
      store.dispatch('getUserInfoActions')
    }
    next()
  } else {
    // 未登录,跳转到登陆界面
    if (whiteList.includes(to.path)) {
      // 数组.includes(值),作用:判断值是否在数组里出现过,出现过原地返回true
      next()
    } else {
      // next强制切换到登录路径,会再次走了有==路由守卫再去匹配路由表
      next('/login')
    }
  }
})
export default router
// 退出登录时，重新登陆，只走相关代码（异步dom切换，不会导致所有的代码重新执行）
// 效果不对：换个账号重新请求用户数据
// 解决：在登录页面，登陆成功后，在发送请求拿到用户信息
// 2.在全局前置路由守卫中写，（路由跳转时，判断再获取）
